﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Server
{
    class UdpServer
    {
        public static UdpServer ins;
        public string ipAddress = "192.168.2.104";
        public int ConnectPort = 5555;
        public string recvMsg;
        public List<string> PlayerList = new List<string>();
        public Dictionary<string, Servers.Client> PListDic = new Dictionary<string, Servers.Client>();

        public Socket socket;
        public EndPoint NowClientEnd;  //现在连接的客户端
        public IPEndPoint serverEnd;   //服务端IP:端口

        byte[] recvData = new byte[1024];
        byte[] sendData = new byte[1024];
        int recvLen;
        Thread connectThread;
        //初始化
        public UdpServer(string ip, string port)
        {
            ins = this;
            serverEnd = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }

        /// <summary>
        /// 每次给RecvStr赋值时执行set方法
        /// </summary>
        public string RecvMsg
        {
            get
            {
                return recvMsg;
            }
            set
            {
                recvMsg = value;
                ShowMsg(string.Format("收到得信息:{0} 字节{1}" ,value, recvLen.ToString()));
                Send("服务端返回:" + value);
            }
        }

        public void Init()
        {
            socket.Bind(serverEnd);
            //定义客户端
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            NowClientEnd = (EndPoint)sender;
            ShowMsg("服务器开启" + serverEnd);
            //开启一个线程连接
            connectThread = new Thread(new ThreadStart(Receive));
            connectThread.Start();
        }

        void Send(string sendStr)
        {
            sendData = new byte[1024];
            sendData = Encoding.UTF8.GetBytes(sendStr);
            socket.SendTo(sendData, sendData.Length, SocketFlags.None, NowClientEnd);
        }
        //服务器接收
        void Receive()
        {
            while (true)
            {
                recvData = new byte[1024];
                recvLen = socket.ReceiveFrom(recvData, ref NowClientEnd);
                //利用RecvStr的set方法处理信息
                RecvMsg = Encoding.UTF8.GetString(recvData, 0, recvLen);
                ShowMsg(string.Format("{0}发来信息:{1}", NowClientEnd, RecvMsg));
                AddClient(NowClientEnd);
            }
        }

        //客户端添加到List和窗口列表, 
        void AddClient(EndPoint ipEnd)
        {
            string ipPort = ipEnd.ToString();
            //判断客户端是否已连接过
            if (PListDic.ContainsKey(ipPort))
            {
                //ShowMsg("客户端已连接过!");
            }
            else
            {
                Servers.Client client = new Servers.Client(this, NowClientEnd);
                PListDic.Add(ipPort, client);
                ShowMsg("客户端添加到列表" + NowClientEnd);
                ServerWin.ins.AddClient(ipPort);
            }
        }

        //连接关闭
        public void Close()
        {
            //关闭线程
            if (connectThread != null)
            {
                connectThread.Interrupt();
                connectThread.Abort();
            }
            //最后关闭socket
            if (socket != null)
                socket.Close();
            ShowMsg("已关闭服务器" + serverEnd);
        }

        void OnApplicationQuit()
        {
            Close();
        }

        //消息显示到窗口列表
        void ShowMsg(string msg)
        {
            ServerWin.ins.ShowMsg(msg);
        }

    }
}

